import tkinter
from md5 import Md5
import requests


class Trans:
    def __init__(self):
        pass

    def trans(self):
        screen = tkinter.Tk()
        # 设置窗口的位置以及大小
        screen.geometry("600x500+450+100")
        screen.title("小利翻译")
        # 创建label对象
        label = tkinter.Label(screen, text="要翻译的文字")
        label.place(x=170, y=150)
        label1 = tkinter.Label(screen, text="翻译的结果为")
        label1.place(x=170, y=190)
        self.u1 = tkinter.StringVar()
        self.u2 = tkinter.StringVar()
        text = tkinter.Entry(screen, textvariable=self.u1)
        text.place(x=260, y=150)
        text1 = tkinter.Entry(screen, textvariable=self.u2)
        text1.place(x=260, y=190)
        self.r = tkinter.IntVar()
        radio = tkinter.Radiobutton(screen, text="英译汉", variable=self.r, value=1)
        radio.place(x=260, y=220)
        radio1 = tkinter.Radiobutton(screen, text="汉译英", variable=self.r, value=2)
        radio1.place(x=330, y=220)
        self.r.set(1)

        # 其中commend的值就是函数名
        button = tkinter.Button(screen, text="翻译", command=self.translate)
        button.place(x=260, y=270)
        # 使用mainloop方法使得窗口显示
        screen.mainloop()

    def translate(self):
        if self.r.get() == 1:
            self.yinghan()
        else:
            self.hanying()
        pass

    def yinghan(self):
        appid = "20220314001124419"
        q = self.u1.get()
        md = Md5()
        md.q = q
        from1 = "en"
        to = "zh"
        salt = "123456"
        sign = md.encry()
        url = "http://api.fanyi.baidu.com/api/trans/vip/translate?q="+q+"&from="+from1+"&to="+to+"&appid="+appid+"&salt="+salt+"&sign="+sign
        re = requests.get(url)
        res = re.json()["trans_result"][0]["dst"]
        print(res)
        self.u2.set(res)
        pass

    def hanying(self):
        appid = "20220314001124419"
        q = self.u1.get()
        md = Md5()
        md.q = q
        from1 = "zh"
        to = "en"
        salt = "123456"
        sign = md.encry()
        url = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=" + q + "&from=" + from1 + "&to=" + to + "&appid=" + appid + "&salt=" + salt + "&sign=" + sign
        re = requests.get(url)
        res = re.json()["trans_result"][0]["dst"]
        print(res)
        self.u2.set(res)
        pass
